<?php

namespace JsonLowCode\Table\Support;

use Closure;
use JsonLowCode\Table;
use JsonLowCode\Table\Column;

class BuildField
{
    /**
     * @param array $row
     * @param Table $table
     * @return array
     */
    public static function make(array $row, Table $table): array
    {
        $columns = $table->getColumns();
        foreach ($row as $field=>$value){
            $rowValue = $value;
            $column = $columns->get($field);
            if ($column){
                $isRender = $column->isRender();
                $maps = $column->getMaps();
                if ($maps){
                    if (is_array($rowValue)){
                        foreach ($value as $k=>$v){
                            $rowValue[$k] = $maps[$v]??$v;
                        }
                    }else{
                        $rowValue = $maps[$rowValue]??$rowValue;
                    }
                    $row[$isRender?$field."_map":$field] = $rowValue;
                }
                $colors = $column->getColors();
                if ($colors){
                    if (is_array($value)){
                        $row[$field."_color"] = $colors;
                    }else{
                        $row[$field."_color"] = $colors[$value]??"";
                    }
                }
                $closure = $column->displays($field);
                if($closure instanceof Closure){
                    $result = call_user_func($closure, $rowValue, $row);
                    $row[$field] = $result;
                }
            }
        }
        return $row;
    }
}
